#pragma once

#include "Connection.hpp"
#include "IOService.hpp"

class Listener : public Connection
{
    static const uint16_t default_port = 0;

public:
    Listener(Reactor*owner,uint16_t port = default_port)
        : _port(port),
          _sock(make_shared<TcpSocket>(port)),
          Connection(owner)
    {
        _sock->BuildSocket(SockType::LISTEN_SOCK);

        FdSetNonBlock(Fd()); // 把fd设置为非阻塞
    }

    virtual int Fd()
    {
        return _sock->GetSockfd();
    }
    virtual void Recver()
    {
        // 非阻塞循环读取
        while (true)
        {
            uint32_t ip_client;
            uint16_t port_client;
            int sockfd= _sock->Accept(ip_client, port_client);

            if (sockfd<0) // 获取新链接失败
            {
                // 判断错误码
                if (errno == EAGAIN || EWOULDBLOCK) // 连接全部读取完毕
                {
                    // 结束函数调用
                    return;
                }
                else if (errno == EINTR) // 被信号中断
                {
                    // 重新accept一次
                    continue;
                }
                else
                {
                    Excepter();
                    return;
                }
            }
            FdSetNonBlock(sockfd); // 把fd设置为非阻塞

            LOG(LogLevel::DEBUG) << "成功获取新连接，fd: " << sockfd;

            auto sock=make_shared<IOService>(Owner(),port_client,ip_client,sockfd);

            // 调用Reactor注册进来的成员函数InsertConnection
            Owner()->InsetConnection(sockfd,sock);
            Owner()->PushTimestamp(sockfd,sock);
        }
    }
    virtual void Sender()
    {
    }
    virtual void Excepter()
    {
        char error_buf[defalut_error_buff_size];
        strerror_r(errno, error_buf, sizeof(error_buf));
        LOG(LogLevel::WARNING) << "error: " << error_buf;

        // 调用Reactor的成员函数DeleteConnection
        Owner()->DleteConnection(Fd());
    }
    ~Listener()
    {
    }

private:
    uint16_t _port;
    SockPtr _sock;
};